angular.module('usercenter.service.auth', [
    "ngResource",
    "ngStorage",
])
/**
 * 用户服务
 * 方法：{
     * 获取短信验证码
     * 注册
     * 登录
     * 获取userId，
     * 获取用户name
     * 注销登录
     * 登录检测
     * }
 */
    .service('usercenter_AuthService', ['$resource','$localStorage','$http','$q',function($resource, $localStorage,$http,$q){
        var $storage = $localStorage.$default({
            cmtname: '',
            cmtuserId: '',
            cmtwxpay_openid: '',
        });
        // 获取验证码
        this.getcode = function(phone) {
            var GetPhoneCode =  $resource(baseurl+'user/sendcode/:acount');
            var acount = "cf_dadao";
            GetPhoneCode.get({acount:acount,phone:phone});
        }
        // 注册
        var UserRegedit =  $resource(baseurl+'user');
        // 注册
        this.register = function (user, success_func, error_func) {
            var UserRegist = $resource(baseurl + 'user');
            user.name = user.phone;
            return UserRegist.save({code: user.code}, user, success_func, error_func);
        }
        // 登录
        var UserLogin =  $resource(baseurl+'user/login');
        this.login=function(user, success_func, error_func){
            var parms = {"name":user.phone,"password":user.password};
            UserLogin.save(parms).$promise.then(function(data){
                if(success_func){
                    success_func();
                }
                $storage.cmtname = data.name;
                $storage.cmtuserId = data.userid;
            },function(error){
                if(error_func){
                    error_func(error);
                }
            });
        }
        // 注销
        this.logout = function() {
            $storage.cmtname = '';
            $storage.cmtuserId = '';
            $storage.cmtwxpay_openid = '';
            $storage.cmtShopcart = {};
        }
        //获取用户id
        this.getUserid = function () {
            if($storage.cmtuserId != ''){
                return $storage.cmtuserId;
            }
            else{
                /*alert("您还未登录,请先登录");*/
            }
        }
        //获取用户的name 为空让他去登录
        this.getUsername = function () {
            if(!$storage.cmtname){
                $location.path("/login");
                return '';
            }else{
                return $storage.cmtname;
            }
        }
        //获取用户信息
        this.getMessg = function(){
            var id = this.getUserid();
            var getuserMessg = $resource(baseurl + "user/:id")
            return getuserMessg.get({id:id})
        }
        //修改用户名
        this.resetName=function(data,success,error){
            var id = this.getUserid();
            var resetname = $resource(baseurl + "user/:id");
            return resetname.save({id:id},data,success,error)
        }
        //获取用户名
        this.getUsername = function () {
            return $storage.cmtname;
        }
        //修改用户头像
        this.setUserhead = function(user){
            var id = this.getUserid();
            var sethead = $resource(baseurl + "user/:id")
            return sethead.save({id:id},user);
        }
        //图片上传
        this.uploadFile = function(imgsrc,img){
            var postData = {
                filename: imgsrc,
                file: img
            };
            var fd = new FormData();
            angular.forEach(postData, function(val, key) {
                fd.append(key, val);
            });
            var deferred = $q.defer();
            $http({
                method:'POST',
                url:baseurl+'picupload',
                data:fd,
                headers: {'Content-Type': undefined},
                transformRequest: angular.identity
            }).success(function(data,status,headers,config){
                deferred.resolve(data);
            }).error(function(data,status,headers,config){
                deferred.reject(data);
            });
            return deferred.promise;
        }

        //缓存用户支付openid
        this.getopenid = function(){
            var openid_res = $resource(pay_config.wxpay_reaurl + "openid");
            //获取OpenID
            if (!$storage.cmtwxpay_openid) {
                var reg = new RegExp("(^|&)" + "code" + "=([^&]*)(&|$)");
                var r = window.location.search.substr(1).match(reg);
                var authcode = "xxxxxxxxxxxxxxxxxx";
                if (r) {
                    authcode = unescape(r[2]);
                    var openid = openid_res.get({wxspid:pay_config.wxpay_spid, code:authcode}).$promise.then(function(data){
                        if (data.openid) {
                            $storage.cmtwxpay_openid = data.openid;
                        } else {
                            console.log("can't get openid by code="+authcode);
                        }
                    }, function(error){
                        console.log("code is invalid");
                    });
                    return openid;
                } else {
                    console.log("can't find code");
                    return $storage.cmtwxpay_openid;
                }
            } else {
                return $storage.cmtwxpay_openid;
            }
        }
    }])

//文件上传
    .service('fileReader',['$q','$log',function($q, $log){
        var onLoad = function(reader, deferred, scope) {
            return function () {
                scope.$apply(function () {
                    deferred.resolve(reader.result);
                });
            };
        };
        var onError = function (reader, deferred, scope) {
            return function () {
                scope.$apply(function () {
                    deferred.reject(reader.result);
                });
            };
        };
        var getReader = function(deferred, scope) {
            var reader = new FileReader();
            reader.onload = onLoad(reader, deferred, scope);
            reader.onerror = onError(reader, deferred, scope);
            return reader;
        };
        var readAsDataURL = function (file, scope) {
            var deferred = $q.defer();
            var reader = getReader(deferred, scope);
            reader.readAsDataURL(file);
            return deferred.promise;
        };
        return {
            readAsDataUrl: readAsDataURL
        };
    }])

/**
 * 用户地址服务
 * 方法：{
     * 获取指定用户的所有地址
     * 删除指定用户的某个地址
     * 新增指定用户的地址
     * 更新地址
     * 设置缓存地址
     * 获取缓存地址
     * }
 */
    .service('usercenter_userAddress',['$resource','usercenter_AuthService',function($resource,usercenter_AuthService){
        var cacheAddress = {
            defaultaddress:"",
        }

        var address =  $resource(baseurl+'usercontact/byuserid/:userid');
        var readdress = $resource(baseurl+'usercontact/:id');
        var newAddress = $resource(baseurl+'usercontact');

        //获取该用户的所有地址
        this.alladdress = function(){
            var userid = usercenter_AuthService.getUserid();
            return address.query({userid:userid});
        }
        //通过地址id获取地址
        this.get_addressbyid = function (contactid) {
            return readdress.get({id: contactid});
        }

        //删除该用户的某个地址
        this.rmaddress = function(contactid){
            return readdress.remove({id:contactid});
        }

        //新增地址
        this.add_address = function(newaddress,success,err){
            newaddress.userid = usercenter_AuthService.getUserid();
            return newAddress.save(newaddress,success,err);
        }

        //更新地址
        this.updateaddress = function(address){
            return readdress.save({id:address.contactid},address);
        }
        //设置默认地址，并缓存
        this.setDefault = function(address){
            var resource = $resource(baseurl + "usercontact/byuserid/setdefault/:userid");
            return resource.get({userid: address.userid, contactid:address.contactid});
        }
        //获取省份
        this.getProvince = function(){
            return $resource("http://api.nonggui8.com/address/province").query();
        }
        //获取城市
        this.getCity = function(provinceId){
            return $resource("http://api.nonggui8.com/address/city/byprovince/:id").query({id:provinceId});
        }
        //获取县
        this.getCounty = function(cityId){
            return $resource("http://api.nonggui8.com/address/county/bycity/:id").query({id:cityId});
        }
    }])
;